//
//  WBMainViewController.swift
//  SinaWeibo
//
//  Created by 张晗 on 2017/1/26.
//  Copyright © 2017年 zhanghan. All rights reserved.
//

import UIKit

class WBMainViewController: UITabBarController {
    
    fileprivate lazy var composeButton = UIButton()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupChlidControllers()
        setupComposeButton()
        
        
    }
    
    @objc fileprivate func composeStatue() {
        print("compose")
    }
}


// MARK: - 设置界面
extension WBMainViewController {
    
    fileprivate func setupChlidControllers() {
        var viewContrllers = [UIViewController]()
        let array = [["className": "WBHomeViewController", "title": "首页", "imageName": "home"],
                     ["className": "WBMessageViewController", "title": "消息", "imageName": "message_center"],
                     ["className": "WXBaseViewController"],
                     ["className": "WBDiscoverViewController", "title": "发现", "imageName": "discover"],
                     ["className": "WBProfileViewController", "title": "我", "imageName": "profile"]]
        
        for dict in array {
            viewContrllers.append(controller(dict: dict))
        }
        self.viewControllers = viewContrllers
    }
    
    fileprivate func setupComposeButton() {
        composeButton.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), backgroundImage: #imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
        composeButton.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), backgroundImage: #imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
        tabBar.addSubview(composeButton)
        
        let itemWidth = tabBar.bounds.width/CGFloat(childViewControllers.count) - 1
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * itemWidth, dy: 0)
        composeButton.addTarget(self, action: #selector(composeStatue), for: .touchUpInside)
    }
    
    private func controller(dict: [String: String]) -> UIViewController {
        guard
            let className = dict["className"],
            let title = dict["title"],
            let imageName = dict["imageName"],
            let vc_class = NSClassFromString(Bundle.main.namespace + "." + className) as? UIViewController.Type
        else {
            print("some value may be nil")
            return UIViewController()
        }
        
        let vc = vc_class.init()
        vc.title = title
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.black], for: .selected)
        return WBNavigationViewController(rootViewController: vc)
    }
}
